package health.lm.com.network.utils;

import android.util.Base64;
import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * Created by Sunqj on 2017/1/6.
 */

public class MyApi {
    //单例实体
    private volatile static MyApi s_instance;
    //网络请求客户端
    //private final OkHttpClient f_client;
    //请求地址
    private String m_apiUrl = "https://www.baidu.com";
    //AES加密key
    private String m_key = "ca751e7aeaf600700933bcb1e609a455";
    //AES加密Vector
    private String m_vector = "ca751e7aeaf60070";
    //接口版本号
    private String m_version = "1.0.0";

    /**
     * 以流的方式添加信任证书
     */
//    private MyApi(InputStream inStream) throws Exception {
//        X509TrustManager trustManager;
//        SSLSocketFactory sslSocketFactory;
//
//        try {
//            trustManager = trustManagerForCertificates(inStream);//以流的方式读入证书
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(null, new TrustManager[]{trustManager}, null);
//            sslSocketFactory = sslContext.getSocketFactory();
//
//        } catch (GeneralSecurityException e) {
//            throw new RuntimeException(e);
//        }
//
//        f_client = new OkHttpClient.Builder()
//                .sslSocketFactory(sslSocketFactory, trustManager)
//                .build();
//    }


    /**
     * 获取API唯一实体
     *
     * @return
     */
    public static MyApi getInstance() {
        if (s_instance == null) {
            s_instance = new MyApi();
        }
        return s_instance;
    }

    /**
     * 使用文件流的方式安装证书
     *
     * @param inStream
     * @throws Exception
     */
//    public static void installCertificate(InputStream inStream) throws Exception {
//        if (s_instance == null) {
//            synchronized (MyApi.class) {
//                if (s_instance == null) {
//                    s_instance = new MyApi(inStream);
//                }
//            }
//        }
//    }

    /**
     * 同步请求
     *
     * @param module
     * @param interfaceCode
     * @param data
     * @return
     * @throws Exception
     */
//    public JSONObject request(String module, String interfaceCode, JSONObject data) throws Exception {
//        //请求报文
//        String requestMsg = generateMessage(module, interfaceCode, data);
//
//        //创建请求体
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestMsg);
//
//        //创建网络请求
//        Request request = new Request.Builder().url(m_apiUrl).post(requestBody).build();
//
//        //执行网络请求
//        Call call = f_client.newCall(request);
//        Response response = call.execute();
//
//        //回执报文
//        String responseMsg = aesDecrypt(response.body().string());
//
//        //返回JSON格式的报文
//        return new JSONObject(responseMsg);
//    }
//
//    public void asyncRequest(String module, String interfaceCode, JSONObject data, final MyApiCallback responseCallback) throws Exception {
//        //请求报文
//        String requestMsg = generateMessage(module, interfaceCode, data);
//
//        //创建请求体
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestMsg);
//
//        //创建网络请求
//        Request request = new Request.Builder().url(m_apiUrl).post(requestBody).build();
//
//        f_client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                responseCallback.onFailure(call, e);
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                //获取
//                try {
//                    JSONObject jsonResponse = new JSONObject(aesDecrypt(response.body().string()));
//
//                    responseCallback.onResponse(call, jsonResponse);
//                } catch (Exception e) {
//
//                }
//            }
//        });
//    }

    /**
     * 加密文本
     *
     * @param plaintext
     * @return
     * @throws Exception
     */
    private String aesEncrypt(String plaintext) throws Exception {
        //获取加密器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

        //获取key的字节内容
        byte[] raw = m_key.getBytes();

        SecretKeySpec spec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(m_vector.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, spec, iv);
        byte[] encrypted = cipher.doFinal(plaintext.getBytes("utf-8"));
        return Base64.encodeToString(encrypted, Base64.NO_WRAP);// 此处使用BASE64做转码。
    }

    public String aesDecrypt(String ciphertext) throws Exception {
        try {
            byte[] raw = m_key.getBytes("ASCII");
            SecretKeySpec spec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(m_vector.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, spec, iv);
            byte[] encrypted1 = Base64.decode(ciphertext.getBytes(), Base64.NO_WRAP);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 生成请求报文
     *
     * @param module        接口模块ID
     * @param interfaceCode 接口ID
     * @param data          接口请求数据
     * @return 返回拼装后加密的Json字符转
     * @throws Exception
     */
    public String generateMessage(String module, String interfaceCode, JSONObject data) throws Exception {
        JSONObject requestData = new JSONObject();

        //版本号
        requestData.put("version", m_version);
        //模块
        requestData.put("module", module);
        //接口编码
        requestData.put("interface", interfaceCode);

        //请求数据
        if (data == null) {
            data = new JSONObject();
        }
        requestData.put("data", data);

        String tempString = requestData.toString();
        Log.e("Tag",tempString);

        JSONObject result = new JSONObject();
        result.put("body", aesEncrypt(tempString));
        Log.e("Tag",result.toString());
        return result.toString();
    }

    /**
     * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
     * certificates have not been signed by these certificates will fail with a {@code
     * SSLHandshakeException}.
     * <p>
     * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
     * set. This is useful in development where certificate authority-trusted certificates aren't
     * available. Or in production, to avoid reliance on third-party certificate authorities.
     * <p>
     * <p>
     * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
     * <p>
     * <p>Relying on your own trusted certificates limits your server team's ability to update their
     * TLS certificates. By installing a specific set of trusted certificates, you take on additional
     * operational complexity and limit your ability to migrate between certificate authorities. Do
     * not use custom trusted certificates in production without the blessing of your server's TLS
     * administrator.
     */
    private X509TrustManager trustManagerForCertificates(InputStream in)
            throws GeneralSecurityException {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
        if (certificates.isEmpty()) {
            throw new IllegalArgumentException("expected non-empty set of trusted certificates");
        }

        // Put the certificates a key store.
        char[] password = "password".toCharArray(); // Any password will work.
        KeyStore keyStore = newEmptyKeyStore(password);
        int index = 0;
        for (Certificate certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificate);
        }

        // Use it to build an X509 trust manager.
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }
        return (X509TrustManager) trustManagers[0];
    }

    /**
     * 添加password
     *
     * @param password
     * @return
     * @throws GeneralSecurityException
     */
    private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); // 这里添加自定义的密码，默认
            InputStream in = null; // By convention, 'null' creates an empty key store.
            keyStore.load(in, password);
            return keyStore;
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    }
}
